package com.ai.aiagent.advisor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import reactor.core.publisher.Flux;

/**
 * 自定义权限校验advisor
 */
@Slf4j
public class PermissionValidationAdvisor implements CallAdvisor, StreamAdvisor {

    private final int order;

    public PermissionValidationAdvisor(int o) {
        this.order = o;
    }

    public void permissionCheck(ChatClientRequest chatClientRequest) {
        // 权限校验逻辑示例：从请求中获取用户信息进行校验
        String user = (String) chatClientRequest.context().get("user");
        log.info("当前用户为：{}", user);
        if (user == null || !hasPermission(user)) {
            log.error(user, "用户无权限访问");
            throw new RuntimeException("用户无权限访问");
        }
    }


    // 模拟权限校验方法
    private boolean hasPermission(String user) {
        // 这里可以替换为实际的权限校验逻辑
        return "admin".equals(user) || "test".equals(user);
    }

    /**
     * 权限校验
     * @param chatClientRequest
     * @param callAdvisorChain
     * @return
     */
    @Override
    public ChatClientResponse adviseCall(ChatClientRequest chatClientRequest, CallAdvisorChain callAdvisorChain) {
        permissionCheck(chatClientRequest);
        return callAdvisorChain.nextCall(chatClientRequest);
    }

    /**
     * 流式权限校验
     * @param chatClientRequest
     * @param streamAdvisorChain
     * @return
     */
    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest, StreamAdvisorChain streamAdvisorChain) {
        // 权限校验逻辑示例：从请求中获取用户信息进行校验
        permissionCheck(chatClientRequest);
        return streamAdvisorChain.nextStream(chatClientRequest);
    }


    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 权限校验的优先级最高
     * @return
     */
    @Override
    public int getOrder() {
        return this.order;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private int order = HIGHEST_PRECEDENCE;

        private Builder() {
        }

        public Builder order(int order) {
            this.order = order;
            return this;
        }

        public PermissionValidationAdvisor build() {
            return new PermissionValidationAdvisor(order);
        }
    }
}
